package com.jacky.demo.opengl;

import android.opengl.GLES20;
import android.opengl.Matrix;

import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

/**
 * Created by lixinquan on 2019/2/14.
 * 正方形
 */
public class Square extends Shape {

    private FloatBuffer vertexBuffer;
    static float squareCoords[] = {
            -0.5f,  0.5f, 0.0f,   // top left
            -0.5f, -0.5f, 0.0f,   // bottom left
            0.5f,  0.5f, 0.0f, // top right
            0.5f, -0.5f, 0.0f   // bottom right
             };

    float color[] = { 0f, 0f, 1.0f, 1.0f }; //顶点统一白色

    private final float[] mMVPMatrix = new float[16];
    private final float[] mProjectMatrix = new float[16];
    private final float[] mViewMatrix = new float[16];
    int mMatrixHandler, mPositionHandle, vColorHandle;

    Square() {
        vertexBuffer = GlUtils.allocateFloatBuffer(squareCoords);
    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {
        //计算宽高比
        float ratio=(float)width/height;
        //设置透视投影
        Matrix.frustumM(mProjectMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
        //设置相机位置
        Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 7.0f, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
        //计算变换矩阵
        Matrix.multiplyMM(mMVPMatrix,0,mProjectMatrix,0,mViewMatrix,0);
    }

    public void draw() {
        GLES20.glUseProgram(mProgram);
        mMatrixHandler= GLES20.glGetUniformLocation(mProgram,"vMatrix");
        GLES20.glUniformMatrix4fv(mMatrixHandler,1,false,mMVPMatrix,0);

        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, 12, vertexBuffer);

        vColorHandle = GLES20.glGetUniformLocation(mProgram , "vColor");
        GLES20.glUniform4fv(vColorHandle , 1 , color , 0);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP , 0, 4);
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }
}
